//
//  JJBundleHelper.m
//  ClaimPlatform_RN
//
//  Created by woshiku on 2018/6/26.
//  Copyright © 2018年 jj. All rights reserved.
//

#import "JJBundleHelper.h"
#import "RCTBundleURLProvider.h"
#import "JJFileHelper.h"
#import "ADUtilHelper.h"
#import "JJLog.h"
#import "JJ_ZGUtils.h"
static NSString *LOG_MODULENAME = @"JJRNUPDATE";

@implementation JJBundleHelper
+(SNBundleHelper*)shared{
    static JJBundleHelper *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[[self class] alloc] init];
    });
    return sharedMyManager;
}
-(NSURL *)getMainBundlePath{
    NSString *appVersion=[JJommonTools snc_softwareVersion];
#ifdef  DEBUG
    NSURL *jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
    self.currentRNBundleVersion=appVersion;
    return jsCodeLocation;
#else
    NSString *jsMainBundlePath=@"";
    NSString *rnBundleVersion=[SNRNFileOperation getLocalRNBundleVersion];
    
    if ([rnBundleVersion isEqualToString:@""]) {
        JJLogInfo(LOG_MODULENAME, @"APPLaunch rnBundleVersion is not exit");
       
        //删除本地所有的RN bundle
        [SNRNFileOperation deleteLocalFile:[SNRNFileOperation getBundleFloderPath]];
        //使用安装包中的rn bundle
        jsMainBundlePath=[[NSBundle mainBundle] pathForResource:@"main" ofType:@"jsbundle"];
        self.currentRNBundleVersion=appVersion;
    }else{
        
        
        BOOL verCmp=[self compareVersionNum:rnBundleVersion CurrentVersion:appVersion];
        if (verCmp) {
            JJLogInfo(LOG_MODULENAME, @"APPLaunch APP version>=rn bundle version");
            [self doZhugeTrackForRnLoad:@"RN热更新-加载成功" UpdateVersion:appVersion FailReason:nil];
            //删除本地Rn热更新信息
            [SNRNFileOperation deleteLocalFile:[SNRNFileOperation getLocalRNBundleFile]];
            //删除本地所有的RN bundle
            [SNRNFileOperation deleteLocalFile:[SNRNFileOperation getBundleFloderPath]];
            jsMainBundlePath=[[NSBundle mainBundle] pathForResource:@"main" ofType:@"jsbundle"];
            self.currentRNBundleVersion=appVersion;
        }else{
            //获取对应RNbundleVersion信息，存储的本地Rnbundle包文件
            NSString *rnBundleVersionFolder=[NSString stringWithFormat:@"%@/\%@%@",[SNRNFileOperation getBundleFloderPath],RNBUNDLEFLODERPRE,rnBundleVersion];
            BOOL rnBundleFileisExit=[SNRNFileOperation localFileIsExit:rnBundleVersionFolder];
            if (rnBundleFileisExit) {
                JJLogInfo(LOG_MODULENAME, @"APPLaunch RnBundle file is exited");
                //存在使用本地的Rn bundle
                NSString *localJsMainBundlePath=[NSString stringWithFormat:@"%@/\%@",rnBundleVersionFolder,MAIN_JSBUNDLE];
                //对应版本的bundle的MD5值
                NSString *bundleFileMD5=[[ADUtilHelper getFileMD5WithPath:localJsMainBundlePath]uppercaseString];
                //本地存储的bundle对应的MD5值
                NSString *localStoreMD5=[SNRNFileOperation getRNBundleMD5Value:rnBundleVersion];
                if ([bundleFileMD5 isEqualToString:localStoreMD5]) {
                    JJLogInfo(LOG_MODULENAME, @"APPLaunch RnBundle file MD5 is right");
                    [self doZhugeTrackForRnLoad:@"RN热更新-加载成功" UpdateVersion:rnBundleVersion FailReason:nil];
                    jsMainBundlePath=localJsMainBundlePath;
                    self.currentRNBundleVersion=rnBundleVersion;
                }else{
                    JJLogWarn(LOG_MODULENAME, @"APPLaunch RnBundle file MD5 is wrong");
                    [self doZhugeTrackForRnLoad:@"RN热更新-加载失败" UpdateVersion:rnBundleVersion FailReason:@"校验MD5失败"];
                    //删除本地对应版本的RN bundle
                    [SNRNFileOperation deleteLocalFile:rnBundleVersionFolder];
                    //删除本地Rn热更新信息
                    [SNRNFileOperation deleteLocalFile:[SNRNFileOperation getLocalRNBundleFile]];
                    jsMainBundlePath=[[NSBundle mainBundle] pathForResource:@"main" ofType:@"jsbundle"];
                    self.currentRNBundleVersion=appVersion;
                }
          }else{
                JJLogInfo(LOG_MODULENAME, @"APPLaunch RnBundle file is not exited");
                [self doZhugeTrackForRnLoad:@"RN热更新-加载失败" UpdateVersion:rnBundleVersion FailReason:@"文件不存在"];
                //删除本地Rn热更新信息
                [SNRNFileOperation deleteLocalFile:[SNRNFileOperation getLocalRNBundleFile]];
                //不存在使用安装包中的bundle
                jsMainBundlePath=[[NSBundle mainBundle] pathForResource:@"main" ofType:@"jsbundle"];
                self.currentRNBundleVersion=appVersion;
             }
        }
        
    }
    return [NSURL URLWithString:jsMainBundlePath];
 #endif
}
/**
 *比较app版本信息大于RnBundle版本信息
 *APP version>=rn bundle version 返回 YES 否则返回 NO
 */
-(BOOL)compareVersionNum:(NSString*)rnVersion CurrentVersion:(NSString*)appVersion{
    NSMutableArray *rnVersionArray =(NSMutableArray*)[rnVersion componentsSeparatedByString:@"."];
    if(rnVersionArray.count<4){
        [rnVersionArray addObject:@"0"];
    }
    NSMutableArray *appVersionArray = (NSMutableArray*)[appVersion componentsSeparatedByString:@"."];
    [appVersionArray addObject:@"0"];
    
    NSString *fullRnVersion=[rnVersionArray componentsJoinedByString:@""];
    NSString *fullAppVersion=[appVersionArray componentsJoinedByString:@""];
    NSInteger fullRnVersionNum=[fullRnVersion integerValue];
    NSInteger fullAppVersioNum=[fullAppVersion integerValue];
    if (fullAppVersioNum>=fullRnVersionNum) {
        return YES;
    }else{
        return NO;
    }
}
//Rn热更新加载埋点
-(void)doZhugeTrackForRnLoad:(NSString*)eventName  UpdateVersion:(NSString*)updateVersion FailReason:(NSString*)failReason{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (!JJ_IsStrEmpty(updateVersion)){
        dic[@"更新版本"] = updateVersion;
    }
    if (!JJ_IsStrEmpty(failReason)){
        dic[@"原因"] = failReason;
    }
    [JJ_ZGUtils zhugeTrackWithName:eventName info:dic];
}
@end
